package system

import (
	"context"
	"regexp"
	"slices"
	"strconv"
	"time"

	"portal/internal/common"
	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddDeptLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	menuModel model.SysMenuModel
	deptModel model.SysDeptModel
}

func NewAddDeptLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddDeptLogic {
	return &AddDeptLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
		deptModel: model.NewSysDeptModel(svcCtx.Orm),
	}
}

func (l *AddDeptLogic) AddDept(req *types.AddDeptRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	err = auth.HasPermission(l.menuModel,l.ctx,"system:dept:edit")
	if err != nil {
		return nil,errorx.Unauthorized
	}
	authinfo,err := auth.GetAuth(l.ctx)
	if err != nil {
		return nil,err
	}
	roles,err := auth.GetRoles(l.ctx)
	if err != nil {
		return nil,err
	}
	dept := &model.SysDept{}
	if len(req.ParentId) <= 0 {
		return nil,errorx.NewBizError(500,"上级节点不能为空")
	}
	parentId,err := strconv.Atoi(req.ParentId)
	if err != nil {
		return nil,errorx.TypeTransError
	}
	dept.ParentId = int64(parentId)
	owndeptId,err := strconv.Atoi(authinfo.DeptId)
	if err != nil {
		return nil,errorx.TypeTransError
	}
	// 判断是否拥有本部门的权限信息
	if isAdmin,_ := auth.IsAdmin(l.ctx); !isAdmin {
		depts,err := getDepts(l.ctx,int64(owndeptId),roles,l.deptModel,&types.ListDeptRequest{})
		if err != nil {
			return nil,errorx.NewBizError(500,"部门信息查询失败")
		}
		isHas := slices.ContainsFunc(depts,func(n *types.Dept)bool{
			return n.DeptId == int64(parentId)
		})
		if !isHas {
			return nil,errorx.Unauthorized
		}
	}

	pDept,err := l.deptModel.FindOne(l.ctx,int64(parentId))
	if err != nil {
		return nil,errorx.SqlSearchError
	}
	dept.Ancestors = pDept.Ancestors + "," + req.ParentId
	if len(req.DeptName) <= 0 {
		return nil,errorx.NewBizError(500,"部门名称不能为空")
	}
	dept.DeptName = req.DeptName
	if req.OrderNum <= 0 {
		return nil,errorx.NewBizError(500,"显示排序不能为空")
	}
	dept.OrderNum = req.OrderNum
	if len(req.Email) > 0 {
		reg := regexp.MustCompile(common.EmailFormat)
		if !reg.MatchString(req.Email) {
			return nil, errorx.NewBizError(500, "邮箱格式不正确")
		}
		dept.Email.String = req.Email
		dept.Email.Valid = true
	}
	if len(req.Phone) > 0 {
		reg := regexp.MustCompile(common.PhoneFormat)
		if !reg.MatchString(req.Phone) {
			return nil,errorx.NewBizError(500,"手机号码格式不正确")
		}
		dept.Phone.String = req.Phone
		dept.Phone.Valid = true
	}
	if len(req.Leader) > 0 {
		dept.Leader.String = req.Leader
		dept.Leader.Valid = true
	}
	if len(req.Status) > 0 {
		dept.Status = req.Status
	}
	dept.CreateBy = authinfo.UserName
	dept.CreateTime = time.Now().Unix()
	dept.UpdateBy = authinfo.UserName
	dept.UpdateTime = time.Now().Unix()
	dept.DelFlag = common.EXIST_FLAG
	deptId,err := l.deptModel.InsertGetId(l.ctx,nil,dept)
	if err != nil {
		return nil,errorx.SqlInsertError
	}
	return &types.CommonResponse{
		Status: 200,
		Msg: "添加成功",
		Data: types.IdResponse{
			Id: deptId,
		},
	},err
}
